#include "appsettings.h"

#include <QtCore/qdebug.h>
#include <QtCore/qsettings.h>
#include <QtCore/qstringlist.h>

static AppSettings s_appSettings;
AppSettings *g_appSettings = &s_appSettings;

AppSettings::AppSettings()
{
    m_isLoaded = false;
}

AppSettings::~AppSettings()
{
}

QVariant AppSettings::get(const QString &key, const QVariant &defaultValue)
{
    if (!m_isLoaded)
        readAll();
    QVariant res = defaultValue;
    if (m_settings.contains(key))
        res = m_settings[key];
    return res;
}

void AppSettings::readAll()
{
    QSettings settingsIni(APPSETTINGS_FILENAME, QSettings::IniFormat);
    foreach (QString k, settingsIni.allKeys())
        m_settings[k] = settingsIni.value(k);
    m_isLoaded = true;
}

void AppSettings::set(const QString &key, const QVariant &value)
{
    if (!m_settings.contains(key) || m_settings[key] != value)
        m_settings[key] = value;
}

void AppSettings::writeAll()
{
    QSettings settingsIni(APPSETTINGS_FILENAME, QSettings::IniFormat);
    QStringList keys = m_settings.keys();
    qSort(keys);
    foreach (QString k, keys)
        settingsIni.setValue(k, m_settings[k]);
}

void AppSettings::writeSetting(const QString &key)
{
    QSettings settingsIni(APPSETTINGS_FILENAME, QSettings::IniFormat);
    settingsIni.setValue(key, m_settings[key]);
}

